<?php

namespace addons\qingdongams\model;

use think\Db;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;

/**
 *工单表
 */
class Workorder extends Model
{
    use SoftDelete;

    protected $name  = 'qingdongams_workorder';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';
// 追加属性
    protected $append = [
        'show_staff_data',
    ];

    public function getCreatetimeAttr($value)
    {
        return date('Y-m-d H:i', $value);
    }

    public function getPayTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i', $value) : '';
    }

    public function getAccepttimeAttr($value)
    {
        if (empty($value)) {
            return $value;
        }
        return date('Y-m-d H:i', $value);
    }

    public function getTrainContentAttr($value)
    {
        if (empty($value)) {
            return [];
        }
        $value=json_decode($value, true);
        if(empty($value)){
            return [];
        }
        foreach ($value as $k=>$v){
          if(empty($v['content'])){
//                continue;
            }
            foreach ($v['content'] as $kc=>$vc){
                if(empty($vc['autograph_url'])){
                    continue;
                }
                $autograph_url=explode(',',$vc['autograph_url']);
                $autograph=[];
                foreach ($autograph_url as $url){
                    $autograph[]=  ['id'=>$vc['autograph_url'],'url'=>cdnurl(File::getUrl($url),true)];
                }
                $vc['autograph']=$autograph;

                $v['content'][$kc]=$vc;
            }
            $value[$k]=$v;
        }
        return $value;
    }

    //
    public function getPayServiceAttr($value)
    {
        if (empty($value)) {
            return [];
        }
        return json_decode($value, true);
    }

    //预计完成时间 expected_end_time
    public function getExpectedEndTimeAttr($value)
    {
        if (empty($value)) {
            return $value;
        }
        return date('Y-m-d H:i', $value);
    }

    public function getStarttimeAttr($value)
    {
        if (empty($value)) {
            return $value;
        }
        return date('Y-m-d H:i', $value);
    }

    public function getEndtimeAttr($value)
    {
        if (empty($value)) {
            return $value;
        }
        return date('Y-m-d H:i', $value);
    }

    public function getProductPartAttr($value)
    {
        $value = json_decode($value, true);
        if (empty($value)) {
            return [];
        }
        $data = [];
        foreach ($value as $v) {
            $cp = CustomerProduct::where(['id' => ['in', $v['customer_product_id']]])->with(['product'])->find();
            if(empty($cp)){
                continue;
            }
            $parts_id = explode(',', $v['parts_id']??'');
            if($cp['product_id']){
                $parts = Parts::where('', 'exp', Db::raw('FIND_IN_SET(' . $cp['product_id'] . ',product_id)'))->select();
                $parts = collection($parts)->toArray();
            }else{
                $parts=[];
            }

            foreach ($parts as $k => $p) {
                $p['is_select'] = in_array($p['id'], $parts_id) ? 1 : 0;
                $parts[$k] = $p;
            }

            $cp['parts'] = $parts;
            $data[] = $cp;
        }
        return $data;
    }

    public function getShowStaffDataAttr($value, $data)
    {
        if (!isset($data['show_staff_id'])) {
            return '';
        }
        $ids = explode(',', $data['show_staff_id']);
        return Staff::where(['id' => ['in', $ids]])->field('id,name,img,post,mobile')->select();
    }

    public function getPartsAttr($value)
    {
        if (empty($value)) {
            return [];
        }
        $value = json_decode($value, true);
        $data = [];
        foreach ($value as $v) {
            $p = Parts::where(['id' => $v['id']])->field('id,name,num,img,unit,price')->find();
            $p['number'] = isset($v['number']) ? $v['number'] : $v['num'];
            $data[] = $p;
        }
        return $data;
    }

    //已使用零件
    public function getUsePartsAttr($value)
    {
        if (empty($value)) {
            return [];
        }
        $value = json_decode($value, true);
        $data = [];
        foreach ($value as $v) {
            $p = Parts::where(['id' => $v['id']])->field('id,name,num,img,unit,price')->find();
            $p['number'] = isset($v['number']) ? $v['number'] : $v['num'];
            $p['is_charge'] = $v['is_charge'] ?? 1;
            $data[] = $p;
        }
        return $data;
    }

    //剩余零件
    public function getSurplusPartsAttr($value)
    {
        if (empty($value)) {
            return $value;
        }
        $value = json_decode($value, true);
        $data = [];
        foreach ($value as $v) {
            $p = Parts::where(['id' => $v['id']])->field('id,name,num,img,unit,price')->find();
            $p['number'] = isset($v['number']) ? $v['number'] : $v['num'];
            $data[] = $p;
        }
        return $data;
    }

    //获取评价附件
    public function getCommentFilesAttr($value)
    {
        $files = explode(',', $value);
        $result = [];
        foreach ($files as $fid) {
            if ($fid) {
                $result[] = cdnurl(File::getUrl($fid), true);
            }
        }

        return $result;
    }
    //回执附件 receipt_file_ids
    public function getReceiptFileIdsAttr($value)
    {
        if(empty($value)){
            return $value;
        }
        $files = explode(',', $value);
        $result = [];
        foreach ($files as $fid) {
            if ($fid) {
                $result[] = cdnurl(File::getUrl($fid), true);
            }
        }

        return $result;
    }

    public function getProductAttr($value)
    {
        if (empty($value)) {
            return '';
        }
        $value = json_decode($value, true);
        if (empty($value)) {
            return '';
        }
        $data = [];
        foreach ($value as $v) {
            if(!isset($v['product_id'])){
                continue;
            }
            $p = Product::where(['id' => $v['product_id']])->field('id,name,num,img,type_id')->find();

            $p['product_id'] = $p['id'] ?? 0;
            $p['number'] = $v['number'] ?? 0;
            $p['end_date'] = $v['end_date'] ?? '';
            $p['desc'] = $v['desc'] ?? '';

            $data[] = $p;
        }
        return $data;
    }

    //获取回款图片
    public function getCollectionImgAttr($value)
    {
        $files = explode(',', $value);
        $result = [];
        foreach ($files as $fid) {
            if ($fid) {
                $result[] = ['id' => $fid, 'url' => cdnurl(File::getUrl($fid), true)];
            }
        }

        return $result;
    }

    //获取评价附件
    public function getAutographUrlAttr($value)
    {
        if(empty($value)){
            return '';
        }
        return cdnurl(File::getUrl($value), true);
    }

    //获取支付附件
    public function getPayFilesAttr($value)
    {
        $files = explode(',', $value);
        $result = [];
        foreach ($files as $fid) {
            if ($fid) {
                $result[] = cdnurl(File::getUrl($fid), true);
            }
        }

        return $result;
    }

    //创建人 员工
    public function createStaff()
    {
        return $this->hasOne(Staff::class, 'id', 'create_staff_id')->field('id,name,img,post');
    }

    //创建人 联系人
    public function createPerson()
    {
        return $this->hasOne(Person::class, 'id', 'person_id')->field('id,account');
    }


    //获取联系人
    public function contacts()
    {
        return $this->hasOne(Contacts::class, 'id', 'contacts_id')
            ->order('is_major desc')->field('id,customer_id,name,mobile,mobilecode,region');
    }

    //获取售后服务用户端
    public function person()
    {
        return $this->hasOne(Person::class, 'id', 'person_id')->field('id,nickname,account');
    }

    //获取售后服务用户端
    public function comments()
    {
        return $this->hasOne(Comment::class, 'relation_id', 'id')->where(['relation_type' => 'workorder'])->field('id,relation_id,content,praise');
    }

    //获取客户
    public function customer()
    {
        return $this->hasOne(Customer::class, 'id', 'customer_id')->field('id,name,industry,level,source');
    }

    //获取评分情况
    public function visit()
    {
        return $this->hasOne(WorkorderVisit::class, 'workorder_id', 'id');
    }

    //获取日程
    public function getevent()
    {
        return $this->hasOne(Event::class, 'relation_id', 'id')->where(['relation_type' => 'workorder']);
    }


    //负责人
    public function ownerStaff()
    {
        return $this->hasOne(Staff::class, 'id', 'owner_staff_id')->field('id,name,img,mobile,email');
    }

    //获取附件记录
    public function file()
    {
        return $this->hasMany(WorkorderFile::class, 'workorder_id', 'id')->with('file')->field('workorder_id,file_id');
    }

    //创建工单
    public static function createWorkorder($params)
    {
        if (isset($params['file_ids'])) {
            $files = $params['file_ids'];
            unset($params['file_ids']);
        } else {
            $files = '';
        }
        //自定义字段
        $other = [];
        foreach ($params as $name => $val) {
            if (strstr($name, 'other_') !== false) {
                $other[$name] = $val;
                unset($params[$name]);
                continue;
            }
            if(empty($params[$name])){
                unset($params[$name]);
                continue;
            }
        }
        $staff = Staff::info();
        if (!empty($staff)) {
            $params['create_staff_id'] = $staff->id;
        }
        if (isset($params['start_time'])) {
            $params['start_time'] = strtotime($params['start_time']);
        }
        if (isset($params['end_time'])) {
            $params['end_time'] = strtotime($params['end_time']);
        }
        if (!isset($params['owner_staff_id']) || empty($params['owner_staff_id'])) {
            $params['owner_staff_id'] = $staff->id;
        }
        $parts = $params['parts'] ?? [];
        foreach ($parts as $pk => $pv) {
            $parts[$pk] = ['id' => $pv['id'], 'number' => $pv['number']];
        }
        $params['parts'] = json_encode($parts);
        $params['status'] = 1;
        if ($params['workorder_type'] == '返厂维修') {
            $params['process'] = 1;
        }
        if (isset($params['product']) && $params['product']) {
            //添加产品
            $product = $params['product'];
            if (is_array($product)){
                $params['product'] = json_encode($product);
            }
            if ($params['workorder_type'] == '产品发货') {
                $addAll = [];
                foreach ($product as $v) {
                    for ($i = 0; $i < $v['number']; $i++) {
                        $addAll[] = [
                            'customer_id' => $params['customer_id'],
                            'product_id' => $v['product_id'],
                            'pay_date' => date('Y-m-d'),
                            'create_staff_id' => $staff->id,
                            'createtime' => time(),
                        ];
                    }
                }
                $CustomerProductModel = new CustomerProduct();
                $customerProductIds = [];
                foreach ($addAll as $ins) {
                    $CustomerProductModel->insert($ins);
                    $customerProductIds[] = $CustomerProductModel->getLastInsID();
                }
                $params['customer_product_id'] = implode(',', $customerProductIds);
            }

        }
        $params['product_part'] = $params['product_part'] ?? [];
        if(is_array($params['product_part'])){
            $params['product_part'] = json_encode($params['product_part'] ?? []);
        }

        $workorderM = new self;
        // 调用当前模型对应的User验证器类进行数据验证
        $result = $workorderM->allowField(true)->save($params);
        $lastId = $workorderM->getLastInsID();
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception($workorderM->getError());
        }

        $otherModel = new WorkorderOther();
        if ($otherModel->save(['id' => $lastId, 'other' => json_encode($other, JSON_UNESCAPED_UNICODE)]) === false) {
            // 验证失败 输出错误信息
            throw new Exception($otherModel->getError());
        }
        if ($files) {
            WorkorderFile::addFiles($files, $lastId);
        }
        //操作记录
        OperationLog::createLog(OperationLog::WORKORDER_TYPE, $lastId, '创建工单');
        $content = '创建工单';
        $paramsSign['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $paramsSign['relation_id'] = $lastId;
        $paramsSign['files'] = $files ?? '';
        $paramsSign['relation_process'] = '创建工单';
        //创建跟进记录
        if(isset($params['customer_id']) && $params['customer_id']){
            StaffSignIn::quickSignIn($params['customer_id'], $content, $paramsSign);
        }

        return $lastId;
    }

    //创建工单
    public static function createCustomerWorkorder($params)
    {
        if (isset($params['file_ids'])) {
            $files = $params['file_ids'];
            unset($params['file_ids']);
        } else {
            $files = '';
        }
        //自定义字段
        $other = [];
        foreach ($params as $name => $val) {
            if (strstr($name, 'other_') !== false) {
                $other[$name] = $val;
                unset($params[$name]);
            }
        }
        if (isset($params['start_time'])) {
            $params['start_time'] = strtotime($params['start_time']);
        }
        if (isset($params['end_time'])) {
            $params['end_time'] = strtotime($params['end_time']);
        }
        $parts = $params['parts'] ?? [];
        foreach ($parts as $pk => $pv) {
            $parts[$pk] = ['id' => $pv['id'], 'number' => $pv['number']];
        }
        $params['parts'] = json_encode($parts);
        $params['status'] = 1;
        if($params['customer_product_id']){
            $customer_product_ids=explode(',',$params['customer_product_id']);
            $product_part=[];
            foreach ($customer_product_ids as $ids){
                $product_part[]=['customer_product_id'=>$ids,'parts_id'=>''];
            }
            $params['product_part'] =$product_part;
        }
        $params['product_part'] = json_encode($params['product_part'] ?? []);
        $params['create_staff_id']=1;
        $params['owner_staff_id']=1;

        $workorderM = new self;
        // 调用当前模型对应的User验证器类进行数据验证
        $result = $workorderM->allowField(true)->save($params);
        $lastId = $workorderM->getLastInsID();
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception($workorderM->getError());
        }

        $otherModel = new WorkorderOther();
        if ($otherModel->save(['id' => $lastId, 'other' => json_encode($other, JSON_UNESCAPED_UNICODE)]) === false) {
            // 验证失败 输出错误信息
            throw new Exception($otherModel->getError());
        }
        if ($files) {
            WorkorderFile::addFiles($files, $lastId);
        }
        //TODO
        $content = '客户提交了维修工单《' . $params['title'] . '》，请尽快处理！';

//        Message::batchMessage(Message::WORKORDER_TYPE, $lastId, $params['show_staff_id'],0, $content, 12);

        return $lastId;
    }

    //接受工单
    public static function acceptWorkorder($params)
    {
        $update = [
            'status' => 2,
            'process' => 0,
            'accept_time' => time()
        ];
        if (isset($params['expected_end_time']) && $params['expected_end_time']) {
            $update['expected_end_time'] = strtotime($params['expected_end_time']);
        }
        if (self::where(['id' => $params['id'], 'status' => 1])->update($update) == false) {
            // 验证失败 输出错误信息
            throw new Exception('更新工单状态失败');
        }

        $staff = Staff::info();
        $row = self::get($params['id']);
        $content = '接受了工单';
        $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $params['relation_id'] = $row['id'];
        $params['relation_process'] = '接受工单';
        $staff                     = Staff::info();
        Message::addMessage(Message::WORKORDER_ACHIEVE,$params['id'],$staff->id,$staff->id);
        //创建跟进记录
        StaffSignIn::quickSignIn($row['customer_id'], $content, $params);
        return true;
    }


    //开始工单
    public static function startWorkorder($params)
    {

        $update = [
            'process' => 1,
            'start_time' => time(),
        ];
        if (isset($params['car_type']) && $params['car_type']) {
            $update['car_type'] = $params['car_type'];
            $update['car_number'] = $params['car_number'] ?? '';
        }

        if (isset($params['start_mileage']) && $params['start_mileage']) {
            $update['start_mileage'] = intval($params['start_mileage']);
        }

        if (self::where(['id' => $params['id'], 'status' => 2])->update($update) == false) {
            // 验证失败 输出错误信息
            throw new Exception('更新工单状态失败');
        }
        //日程开始
        Event::where(['relation_type' => 'workorder', 'relation_id' => $params['id']])
            ->update(['status' => 1]);
        $row = self::get($params['id']);
        $content = '开始了工单<br>备注:'.$params['desc']??'';
        $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $params['relation_id'] = $row['id'];
        $params['relation_process'] = '开始工单';
        //创建跟进记录
        StaffSignIn::quickSignIn($row['customer_id'], $content, $params);
        return true;
    }

    //录入零件
    public static function inputParts($params)
    {
        $parts = $params['parts'] ?? [];

        $update = [];
        if ($parts) {
            $data = [];
            foreach ($parts as $v) {
                $data[] = [
                    'id' => $v['id'],
                    'number' => $v['number']
                ];
            }
            $update['parts'] = json_encode($data);
        }

        if (self::where(['id' => $params['id']])->update($update) == false) {
            // 验证失败 输出错误信息
            throw new Exception('更新工单状态失败');
        }

        $row = self::get($params['id']);
        $content = '录入携带配件信息';
        $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $params['relation_id'] = $row['id'];
        $params['relation_process'] = '录入配件';
        //创建跟进记录
        StaffSignIn::quickSignIn($row['customer_id'], $content, $params);
        return true;
    }


    /**
     *修改工单信息
     */
    public static function updateWorkorder($params)
    {
        $row = self::get($params['id']);

        if (isset($params['file_ids'])) {
            $files = $params['file_ids'];
            unset($params['file_ids']);
        } else {
            $files = '';
        }
        if (isset($params['files'])) {
            $files = $params['files'];
            unset($params['files']);
        }

        //自定义字段
        $other = [];
        foreach ($params as $name => $val) {
            if (strstr($name, 'other_') !== false) {
                $other[$name] = $val;
                unset($params[$name]);
            }
            if(empty($val)){
                unset($params[$name]);
            }
        }
        if (isset($params['start_time'])) {
            $params['start_time'] = strtotime($params['start_time']);
        }
        if (isset($params['workorder_type'])) {
            unset($params['workorder_type']);
        }
        if (isset($params['end_time'])) {
            $params['end_time'] = strtotime($params['end_time']);
        }
        if (isset($params['product']) && $params['product']) {
            $product = $params['product'];

            if (is_array($product)){
                $params['product'] = json_encode($product);
            }
            if ($row->workorder_type == '产品发货') {

                $addAll = [];
                $staff = Staff::info();

                foreach ($product as $v) {
                    for ($i = 0; $i < $v['number']; $i++) {
                        $addAll[] = [
                            'customer_id' => $params['customer_id'],
                            'product_id' => $v['product_id'],
                            'pay_date' => date('Y-m-d'),
                            'create_staff_id' => $staff->id,
                            'createtime' => time(),
                        ];
                    }
                }
                $CustomerProductModel = new CustomerProduct();
                $customerProductIds = [];
                foreach ($addAll as $ins) {
                    $CustomerProductModel->insert($ins);
                    $customerProductIds[] = $CustomerProductModel->getLastInsID();
                }
                $CustomerProductModel
                    ->where(['id' => ['in', explode(',', $row['customer_product_id'])]])->delete();
                $params['customer_product_id'] = implode(',', $customerProductIds);
            }
        }
        if(isset($params['appointment_time'])){
            $params['appointment_time']=$params['appointment_time']?:NULL;
        }
        $params['product_part'] = json_encode($params['product_part'] ?? []);
        if ($row->workorder_type == '返厂维修') {
            $params['process'] = 1;
        }
        $parts = $params['parts'] ?? [];
        foreach ($parts as $pk => $pv) {
            $parts[$pk] = ['id' => $pv['id'], 'number' => $pv['number']];
        }
        $params['parts'] = json_encode($parts);

        $customer = new self;
        // 调用当前模型对应的User验证器类进行数据验证
        $result = $customer->allowField(true)->isUpdate(true)->save($params, ['id' => $params['id']]);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception($customer->getError());
        }

        //日程 修改信息
        if (isset($params['owner_staff_id'])) {
            $updateEvent = [
                'title' => $params['title'],
                'staff_id' => $params['owner_staff_id'],
            ];
            $eventModel = new Event();
            $eventModel->allowField(true)->save($updateEvent, ['relation_type' => 'workorder', 'relation_id' => $params['id']]);
        }

        $otherModel = new WorkorderOther();
        if ($otherModel->isUpdate(true)->save([
                'id' => $params['id'],
                'other' => json_encode($other, JSON_UNESCAPED_UNICODE)
            ]) === false) {
            // 验证失败 输出错误信息
            throw new Exception($otherModel->getError());
        }
        if ($files) {
            WorkorderFile::editFiles($files, $params['id']);
        }

        return true;
    }

    /**
     * 指派工单
     * @desc 备注
     * @update_date 2021/7/9 更新时间
     * @author zhangwei
     */
    public static function assignWorkorder($id, $staff_id, $desc)
    {
        $row = self::get($id);

        $update = [
            'owner_staff_id' => $staff_id,
            'status' => 1];
        if ($row['workorder_type'] == '返厂维修') {
            $update['process'] = 1;
        }
        $result = self::where(['id' => $id])->update($update);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception('修改信息错误');
        }
        //日程 修改指派人
        Event::where(['relation_type' => 'workorder', 'relation_id' => $id])->update(['staff_id' => $staff_id]);

        $staff = Staff::info();
        $transferStaff = Staff::get($staff_id);
        $content = '将工单指派给[' . $transferStaff['name'] . ']' . '备注:' . $desc;

        $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $params['relation_id'] = $id;
        $params['relation_process'] = '指派工单';
        //创建跟进记录
        StaffSignIn::quickSignIn($row['customer_id'], $content, $params);
        //发送通知
        Message::addMessage(Message::WORKORDER_ACHIEVE, $id, $row->owner_staff_id, $staff->id,
            "任务《{$row['title']}》已被指派给其他员工，请您及时审阅！");
        Message::addMessage(Message::WORKORDER_ACHIEVE, $id, $staff_id, $staff->id,
            $staff->name . '指派给您一项任务，请您及时审阅');
        return true;
    }


    /**
     * 转派工单
     * @desc 备注
     * @update_date 2021/7/9 更新时间
     * @author zhangwei
     */
    public static function transferWorkorder($id, $staff_id, $desc='')
    {
        $workorder=self::get($id);

        $result = self::where(['id' => $id])
            ->update(['owner_staff_id' => $staff_id, 'status' => 1]);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception('修改信息错误');
        }
        $staff = Staff::info();
        $transferStaff = Staff::get($staff_id);

        //日程 修改指派人
        Event::where(['relation_type' => 'workorder', 'relation_id' => $id])->update(['staff_id' => $staff_id]);

        $row = self::get($id);
        $content = '将工单转派给[' . $transferStaff['name'] . ']' . '原因:' . $desc;
        $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $params['relation_id'] = $id;
        $params['relation_process'] = '转派工单';
        //创建跟进记录
        StaffSignIn::quickSignIn($row['customer_id'], $content, $params);
        //发送通知
        Message::addMessage(Message::WORKORDER_ACHIEVE, $id, $workorder->owner_staff_id, $staff->id);
        Message::addMessage(Message::WORKORDER_ACHIEVE, $id, $staff_id, $staff->id);

        return true;
    }

    /**
     * 工单签到
     * @desc
     * @update_date 2021/7/10 更新时间
     * @author zhangwei
     */
    public static function workorderSign($id, $desc, $params)
    {
        $workorder = self::get($id);
        $update = [
            'process' => 2,//到达目标位置
            'stock_up_time' => time(),
        ];
        if (isset($params['end_mileage']) && $params['end_mileage']) {
            $params['end_mileage']=intval($params['end_mileage']);
            if ($params['end_mileage'] <= $workorder['start_mileage']) {
                throw new Exception('结束公里数不能小于起始公里数');
            }
            //根据 起始公里数 ，录入行程费用
            $mileage = $params['end_mileage'] - $workorder['start_mileage'];
            $mileage_consume = [
                'title' => $workorder['title'] . '-路程费用',
                'number' => Consume::getNumber(),
                'customer_id' => $workorder['customer_id'],
                'relation_id' => $id,
                'relation_type' => Consume::WORKORDER_TYPE,
                'submit_date' => date('Y-m-d'),
                'remark' => '',
                'money' => Consume::getMileageMoney($mileage)
            ];
            $files = StaffSignIn::where(['relation_type' => StaffSignIn::WORKORDER_TYPE, 'relation_id' => $id])
                ->column('file_ids');
            $files[] = $params['file_ids'];

            $mileage_consume['detail'][] = [
                'consume_date' => date('Y-m-d'),
                'consume_type' => '交通费',
                'consume_money' => Consume::getMileageMoney($mileage),
                'mileage' => $mileage,
                'car_type' => $workorder['car_type'],
                'car_number' => $workorder['car_number'],
                'start_mileage' => $workorder['start_mileage'],
                'end_mileage' => $params['end_mileage'],
                'file_ids' => implode(',', $files)
            ];
            Consume::createConsume($mileage_consume);

            $update['end_mileage'] = $params['end_mileage'];
        }


        $result = self::where(['id' => $id])->update($update);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception('修改信息错误');
        }

        $row = self::get($id);
        $content = '已到达客户位置<br/>备注:'.$desc;
        $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $params['relation_id'] = $row['id'];
        $params['file_ids'] = $params['file_ids'] ?? '';
        $params['relation_process'] = '到达客户位置';
        //创建跟进记录
        StaffSignIn::quickSignIn($row['customer_id'], $content, $params);

        return true;
    }

    /**
     * 终止流程
     * @desc
     * @update_date 2021/7/10 更新时间
     * @author zhangwei
     */
    public static function cancelWorkorder($id, $desc)
    {

        $result = self::where(['id' => $id])->update([
            'status' => 9,//取消工单
        ]);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception('修改信息错误');
        }

        $staff = Staff::info();

        //日程 取消
        Event::where(['relation_type' => 'workorder', 'relation_id' => $id])->update(['status' => 3]);

        $row = self::get($id);
        $content = '终止流程，备注:' . $desc;
        $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $params['relation_id'] = $row['id'];
        $params['relation_process'] = '终止流程';
        //创建跟进记录
        StaffSignIn::quickSignIn($row['customer_id'], $content, $params);
        //发送通知
        Message::addMessage(Message::WORKORDER_TYPE, $id, $row->owner_staff_id, $staff->id,
            $staff->name . '终止任务《' . $row->title . '》，请您及时审阅');
        return true;
    }

    /**
     * 终止流程
     * @desc
     * @update_date 2021/7/10 更新时间
     * @author zhangwei
     */
    public static function failWorkorder($id, $desc)
    {

        $result = self::where(['id' => $id])->update([
            'status' => 9,//取消工单
        ]);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception('修改信息错误');
        }

        $staff = Staff::info();

        $workorder = self::get($id);
        //日程 取消
        Event::where(['relation_type' => 'workorder', 'relation_id' => $id])->update(['status' => 3]);

        $row = self::get($id);
        $content = $workorder['workorder_type'].'任务终止，备注:' . $desc;
        $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $params['relation_id'] = $row['id'];
        $params['relation_process'] = '任务终止';
        //创建跟进记录
        StaffSignIn::quickSignIn($row['customer_id'], $content, $params);
        //发送通知
        Message::addMessage(Message::WORKORDER_TYPE, $id, $row->owner_staff_id, $staff->id,
            $staff->name . '任务终止《' . $row->title . '》，请您及时审阅');
        return true;
    }
    //回访工单
    public static function visitWorkorder($params)
    {

        $result = self::where(['id' => $params['id']])->update([
            'is_visit' => 1,//回访
        ]);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception('修改信息错误');
        }

        $data = [
            'workorder_id' => $params['id'],//
            'satisfaction' => $params['satisfaction'],//
            'visit_time' => $params['visit_time'],//回访时间
            'visit_desc' => $params['visit_desc'],//回访意见
            'visit_opinion' => $params['visit_opinion'],//
            'visit_service' => $params['visit_service'],//
            'visit_skill' => $params['visit_skill'],//
            'skill_score' => $params['skill_score'],//
            'service_score' => $params['service_score'],//
            'opinion_score' => $params['opinion_score'],//
        ];
        $visit = new WorkorderVisit();
        $visit->save($data);

        $row = self::get($params['id']);
        $content = '回访工单';
        $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $params['relation_id'] = $row['id'];
        $params['relation_process'] = '回访工单';
        //创建跟进记录
        StaffSignIn::quickSignIn($row['customer_id'], $content, $params);

        return true;
    }

    //回执工单
    public static function receiptWorkorder($params)
    {

        $result = self::where(['id' => $params['id']])->update([
            'receipt_file_ids' => $params['receipt_file_ids'],//回访
            'receipt_date' => $params['receipt_date'],//回访
        ]);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception('修改信息错误');
        }


        $row = self::get($params['id']);
        $content = '回执工单';
        $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $params['relation_id'] = $row['id'];
        $params['relation_process'] = '回执工单';
        $params['file_ids'] = $params['receipt_file_ids'];
        //创建跟进记录
        StaffSignIn::quickSignIn($row['customer_id'], $content, $params);

        return true;
    }

    /**
     * 撤销工单
     * @desc
     * @update_date 2021/7/10 更新时间
     * @author zhangwei
     */
    public static function revokeWorkorder($id, $desc)
    {
        $result = self::where(['id' => $id])->update([
            'status' => 1,//取消工单
            'process' => 0,
        ]);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception('修改信息错误');
        }

        $staff = Staff::info();

        $row = self::get($id);
        $content = '撤销工单，备注:' . $desc;
        $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $params['relation_id'] = $row['id'];
        $params['relation_process'] = '撤销工单';
        //创建跟进记录
        StaffSignIn::quickSignIn($row['customer_id'], $content, $params);
        //发送通知
        Message::addMessage(Message::WORKORDER_TYPE, $id, $row->owner_staff_id, $staff->id,
            $staff->name . '撤销任务《' . $row->title . '》，请您及时审阅');
        return true;
    }

    /**
     * 签名去人
     * @desc
     * @update_date 2021/7/10 更新时间
     * @author zhangwei
     */
    public static function autograph($id, $url)
    {
        $result = self::where(['id' => $id])->update([
            'is_autograph' => 1,//签名
            'autograph_url' => $url,
        ]);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception('修改信息错误');
        }

        $staff = Staff::info();
        $row = self::get($id);
        $content = '客户签字确认';
        $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $params['relation_id'] = $row['id'];
        $params['relation_process'] = '签字';
        $params['file_ids'] =$url;
        //创建跟进记录
        StaffSignIn::quickSignIn($row['customer_id'], $content, $params);

        return true;
    }


    /**
     * 完结工单
     * @desc 备注
     * @update_date 2021/7/10 更新时间
     * @author zhangwei
     */
    public static function completeWorkorder($id, $desc, $params)
    {
        $row = self::where(['id' => $id])->find();

        $update = [
            'status' => 2,//进行中
            'process' => 3,//录入零件 待录入费用
            'train_content' => json_encode($params['train_content'] ?? [],JSON_UNESCAPED_UNICODE),
            'end_time' => time()
        ];
        if($desc){
            $update['results']=$desc;
        }
        if(isset($params['file_ids']) && $params['file_ids']){
            $update['complate_file']=$params['file_ids'];
        }
        $use_parts = $params['use_parts'] ?? [];
        $pay_service = $params['pay_service'] ?? [];
        $new_use_parts = [];
        foreach ($use_parts as $v) {
            $new_use_parts[] = ['id' => $v['id'], 'number' => $v['number']];
        }

        $use_parts = $new_use_parts;
        if ($row['parts'] && $use_parts) {//计算剩余零件
            $parts=$row['parts'];
            $parts_key = [];
            foreach ($parts as $v) {
                $parts_key[$v['id']] = $v['number'];
            }
            $use_parts_key = [];
            foreach ($use_parts as $v) {
                $use_parts_key[$v['id']] = $v['number'];
            }
            $surplus_parts = [];
            foreach ($parts_key as $k => $number) {
                if (isset($use_parts_key[$k])) {
                    $number = $number - $use_parts_key[$k];
                    $number = $number > 0 ? $number : 0;
                }
                $surplus_parts[] = ['id' => $k, 'number' => $number];
            }
            $update['surplus_parts'] = json_encode($surplus_parts);
        }

        !empty($use_parts) && $update['use_parts'] = json_encode($use_parts);
        !empty($pay_service) && $update['pay_service'] = json_encode($pay_service);

        $update['aftermarket_ids'] = $params['aftermarket_ids'] ?? '';//方案id
        $update['aftermarket_text'] = $params['aftermarket_text'] ?? '';//其他方案

        isset($params['resolved_results']) && $update['resolved_results'] = $params['resolved_results'];//
        isset($params['complete_contact']) && $update['complete_contact'] = $params['complete_contact'];//
        $update['complete_name'] = $params['complete_name'] ?? '';//

        isset($params['mobile_result']) && $update['mobile_result'] = $params['mobile_result'];//电话结果 ，  1 已解决 11 上门服务 12 返厂维修
        isset($params['remarks']) && $update['remarks'] = $params['remarks'];//
        isset($params['desc']) && $update['desc'] = $params['desc'];//
        isset($params['is_mobile']) && $update['is_mobile'] = $params['is_mobile'];//

        if (in_array($row['workorder_type'], ['上门安装', '返厂维修'])) {//
            $update['process'] = 9;
            $update['status'] = 3;//已完成
        } elseif (in_array($row['workorder_type'], ['设计工单', '生产工单', '配件配送', '产品发货'])) {
            $update['process'] = 9;
            $update['status'] = 3;//已完成
        } elseif ($row['workorder_type'] == '电话售后') {
            if(empty($use_parts)){//不需要发送配件 直接完成
                $update['process'] = 9;
                $update['status'] = 3;//已完成
            }
        }

        $result = self::where(['id' => $id])->update($update);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception('修改信息错误');
        }
        if ($row['workorder_type'] == '电话售后' && $use_parts) {
            //自动发货审批人

            $customerInfo = Customer::where(['id' => $row['customer_id']])->find();
            $addWorkorder = [
                'workorder_number' => self::getWorkorderNumber(),
                'workorder_type' => '配件配送',
                'title' => '配件配送',
                'customer_id' => $customerInfo['id'],
                'contacts_id' => $row['contacts_id'],
                'address' => $customerInfo['address'],
                'address_detail' => $customerInfo['address_detail'],
                'lng' => $customerInfo['lng'],
                'lat' => $customerInfo['lat'],
                'priority' => '一般',
                'create_staff_id' => $row['owner_staff_id'],
                'owner_staff_id' => $row['owner_staff_id'],
                'parts' => $use_parts
            ];
            self::createWorkorder($addWorkorder);

        }

        $staff = Staff::info();
        $row = self::get($id);

        if ($row['workorder_type'] == '上门维修') {
            $res = $row['resolved_results'];
            $res = ($res == 1) ? '已解决' : (($res == 9) ? '未解决' : '返厂维修');
            $content = '完成了工单;' . '<br>处理结果:' . $res;
        } elseif ($row['workorder_type'] == '上门安装') {
            $res = $row['resolved_results'];
            if($res == 1){//安装成功
                CustomerProduct::where(['id' => ['in', $row['customer_product_id']]])->update([
                    'status' => 3
                ]);
            }
            $res = ($res == 1) ? '安装成功' : (($res == 9) ? '安装失败' : '返厂维修');

            $content = '完成了工单;' . '<br>处理结果:' . $res;
        } else {
            $content = '完成了工单;' . '<br>处理结果:' . $desc;
        }

        $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $params['relation_id'] = $row['id'];
        $params['file_ids'] = $params['file_ids'] ?? '';
        $params['relation_process'] = '完成工单';
        //创建跟进记录
        StaffSignIn::quickSignIn($row['customer_id'], $content, $params);
        //发送通知
        Message::addMessage(Message::WORKORDER_TYPE, $id,$row->owner_staff_id,$staff->id,$staff->name . '《' . $row->title . '》任务已完成，请您继续操作');
//发送通知
        if($update['status'] == 3){
            self::setComplete($row['id']);
        }
        return true;
    }

    /**
     * 填写维修结果
     * @desc 备注
     * @update_date 2021/7/10 更新时间
     * @author zhangwei
     */
    public static function repairResult($id, $params)
    {
        $row = self::where(['id' => $id])->find();
        $staff = Staff::info();
        if ($params['resolved_results'] == 1) {//维修成功
            $update = [
                'status' => 2,//处理中
                'process' => 3,//维修成功 待提交费用
                'resolved_results' => $params['resolved_results'] ?? 0,
                'is_replace' => $params['is_replace'] ?? 0,
                'is_recovery' => $params['is_recovery'] ?? 0,
                'maintain' => $params['maintain'] ?? '',
                'results' => $params['results'] ?? '',
                'start_time' => strtotime($params['start_time']),
                'end_time' => time()
            ];
            if ($row['is_over'] == 2) {//未过保
//                $update['process']=5;
            }
            $use_parts = $params['use_parts'] ?? [];
            $update['use_parts'] = [];
            foreach ($use_parts as $k => $n) {
                $update['use_parts'][] = ['id' => $n['id'], 'number' => $n['number'] ?? 0];
            }
            $update['use_parts'] = json_encode($update['use_parts']);


        } else {//维修失败
            $update = [
                'status' => 2,//处理中
                'process' => 2,
                'resolved_results' => $params['resolved_results'] ?? 0,
                'is_replace' => $params['is_replace'] ?? 0,
                'is_recovery' => $params['is_recovery'] ?? 0,
                'maintain' => $params['maintain'] ?? '',
                'results' => $params['results'] ?? '',
                'start_time' => strtotime($params['start_time']),
//                'owner_staff_id' => $row->create_staff_id
            ];
            $use_parts = $params['use_parts'] ?? [];
            $update['use_parts'] = [];
            foreach ($use_parts as $k => $n) {
                $update['use_parts'][] = ['id' => $n['id'], 'number' => $n['number'] ?? 0];
            }
            $update['use_parts'] = json_encode($update['use_parts']);
        }
        $result = self::where(['id' => $id])->update($update);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception('修改信息错误');
        }

        //日程开始
        Event::where(['relation_type' => 'workorder', 'relation_id' => $params['id']])
            ->update(['status' => 1]);

        $row = self::get($id);
        if ($update['process'] == 2) {
            $content = '填写维修结果<br>' . '处理结果:维修失败';
            Message::addMessage(Message::WORKORDER_TYPE, $id, $row->owner_staff_id, $staff->id,
                $staff->name . '的工单《' . $row->title . '》维修失败，请您及时处理');
        } else {
            $content = '填写维修结果<br>' . '处理结果:维修成功';
            Message::addMessage(Message::WORKORDER_TYPE, $id, $row->owner_staff_id, $staff->id,
                $staff->name . '的工单《' . $row->title . '》维修成功，请您录入相关费用！');
        }
        $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $params['relation_id'] = $row['id'];
        $params['file_ids'] = $params['file_ids'] ?? '';
        $params['relation_process'] = '填写维修结果';
        //创建跟进记录
        StaffSignIn::quickSignIn($row['customer_id'], $content, $params);

        return true;
    }

    /**
     * 录入工单费用
     */
    public static function enterWorkorderMoney($id, $params)
    {
        $update = [
            'status' => 2,//处理中
            'process' => 7,//费用待审核
        ];
        $pay_service = $params['pay_service'] ?? [];
        $update['pay_service'] = json_encode($pay_service);
        $update['total_money'] = $params['total_money'] ?? 0;//总费用
        $update['discount_money'] = $params['discount_money'] ?? 0;//优惠费用
        $update['money'] = $params['total_money'] - $update['discount_money'];//当前价格
        $update['tax'] = $params['tax'] ?? '';//当前价格
        $update['collection_img'] = $params['collection_img'] ?? '';//
        $update['collection_deposit'] = $params['collection_deposit'] ?? '';//
        $update['collection_account'] = $params['collection_account'] ?? '';
        $update['collection_name'] = $params['collection_name'] ?? '';//
        $update['is_charge']=$params['is_charge']??1;//是否收费 1收费 2不收费
        $update['use_parts'] = [];

        $use_parts = $params['use_parts'] ?? [];
        foreach ($use_parts as $k => $n) {
            $update['use_parts'][] = [
                'id' => $n['id'],
                'number' => $n['number'] ?? 0,
                'is_charge' => $n['is_charge'] ?? 1,
            ];
        }
        $update['use_parts'] = json_encode($update['use_parts']);
        $flow = Flow::getsteplist(Flow::WORKORDER_STATUS);
        $update['flow_id'] = $flow['flow_id'];
        $update['order_id'] = $flow['order_id'];

        if ($flow['status'] == 0) {//发起人自选
            if (empty($params['flow_staff_ids'])) {
                throw new Exception('审批人必须选择');
            }
            $update['flow_staff_ids'] = trim($params['flow_staff_ids']);
        } else {
            $update['flow_staff_ids'] = trim($flow['flow_staff_ids']);
        }
        $update['check_status'] = 1;
        if ($flow['status'] == 1) {//固定审批
            //发送审批通知
            Flow::sendStepRecord($flow,Flow::WORKORDER_STATUS, $id);
        } else {//发起人自选 依次审批
            $staff_id   = explode(',', $params['flow_staff_ids'])[0];
            if ($staff_id) {
                ExamineRecord::addExaminse(ExamineRecord::WORKORDER_TYPE, $id, $staff_id);
            }
        }

        $result = self::where(['id' => $id])->update($update);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception('修改信息错误');
        }

        $row = self::get($id);
        $content = '录入维修费用<br> 金额:' . $update['money'];
        $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $params['relation_id'] = $row['id'];
        $params['file_ids'] = $params['file_ids'] ?? '';
        $params['relation_process'] = '录入维修费用';
        //创建跟进记录
        StaffSignIn::quickSignIn($row['customer_id'], $content, $params);

        return true;
    }

    //财务确认回款
    public static function financialAudit($workorder_id)
    {

        $row = self::where(['id' => $workorder_id])->find();
        //设置产品编号
        self::where(['id' => $workorder_id])->update(['is_financial_audit' => 1]);

        $content = '财务确认收款';
        $data['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $data['relation_id'] = $row['id'];
        $data['relation_process'] = '确认收款';
        //创建跟进记录
        StaffSignIn::quickSignIn($row['customer_id'], $content, $data);
        $staff=Staff::info();
        Message::setRead(Message::WORKORDER_RECEIVABLES,$workorder_id,$staff->id);
        return true;
    }

    //设置产品编号
    public static function setProductNumber($workorder_id, $params)
    {

        $row = self::where(['id' => $workorder_id])->find();
        $staff = Staff::info();
        //设置产品编号
        self::where(['id' => $workorder_id])->update(['process' => 2, 'stock_up_time' => time()]);
        $content = '录入了产品编号';
        $self = new self();
        $self->allowField(true)->save($params, ['id' => $params['workorder_id']]);

        $data['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $data['relation_id'] = $row['id'];
        $data['relation_process'] = '设置产品编号';
        //创建跟进记录
        StaffSignIn::quickSignIn($row['customer_id'], $content, $data);
        return true;
    }

    //设置产品编号
    public static function setPartsNumber($workorder_id, $params)
    {

        $row = self::where(['id' => $workorder_id])->find();
        $staff = Staff::info();
        //设置产品编号
        self::where(['id' => $workorder_id])->update(['process' => 2, 'stock_up_time' => time()]);
        $content = '提交配送信息成功';
        $self = new self();
        $self->allowField(true)->save($params, ['id' => $params['workorder_id']]);

        $data['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $data['relation_id'] = $row['id'];
        $data['relation_process'] = '提交配送信息';
        //创建跟进记录
        StaffSignIn::quickSignIn($row['customer_id'], $content, $data);
        return true;
    }

    //添加物流信息 发货
    public static function setLogistics($workorder_id, $product_ids)
    {
        $row = self::where(['id' => $workorder_id])->find();
        $update = ['process' => 3];
        if ($row['workorder_type'] == '产品发货') {//运输中
//            $customer_product_id=$row['customer_product_id']??'';
//            $customer_product_id=explode(',',$customer_product_id);
            CustomerProduct::where(['id' => ['in', $product_ids]])->update([
                'status' => 1
            ]);
        } else if ($row['workorder_type'] == '返厂维修') {
            $update['process'] = 8;//等待物流到货
        }
        self::where(['id' => $workorder_id])->update($update);

        $content = '提交了物流信息';
        $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $params['relation_id'] = $workorder_id;
        $params['relation_process'] = '添加物流信息';
        //创建跟进记录
        StaffSignIn::quickSignIn($row['customer_id'], $content, $params);

        return true;
    }
    //添加品质异常单
    public static function addProgress($params)
    {
        $staff=Staff::info();
        //填写进度
        $model = new WorkorderProgress();
        $params['create_staff_id'] = $staff->id;
        $model->save($params);
        $workorderModel = new self();
        $row = $workorderModel->get($params['workorder_id']);
        $flow_staff_ids = explode(',', trim($row['flow_staff_ids'], ','));
        $check_staff_ids = explode(',', trim($row['check_staff_ids'], ','));
        $check_staff_ids[] = $staff->id;
        $diff = array_diff($flow_staff_ids, $check_staff_ids);
        $diff = array_values($diff);
        if (empty($diff)) {
            $workorderModel->save([
                'status' => 3,
                'check_status' => 2,
                'check_staff_ids' => implode(',', $check_staff_ids)
            ], ['id' => $row->id]);

            Message::addMessage(Message::WORKORDER_TYPE, $row->id, $row['create_staff_id'], $staff->id, $staff->name . '已经完成了品质异常单，请及时查看！');
        } else {
            //处理中
            $workorderModel->save([
                'check_staff_ids' => implode(',', $check_staff_ids),
                'status' => 2,
                'owner_staff_id' => $diff[0],
            ], ['id' => $row->id]);
            Message::addMessage(Message::WORKORDER_TYPE, $row->id, $diff[0], $row['create_staff_id'], $staff->name . '提交了一个品质异常单需要您处理！');
        }

        $content = '提交异常分析结果';
        $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
        $params['relation_id'] = $params['workorder_id'];
        $params['relation_process'] = '提交异常分析结果';
        //创建跟进记录
        StaffSignIn::quickSignIn($row['customer_id'], $content, $params);
        return true;
    }
    //取消测试/继续测试
    public static function continueTest($id, $is_continue)
    {
        $workorder = self::where(['id' => $id])->find();
        if(empty($workorder)){
            return false;
        }
        if ($is_continue == 1) {//继续维修
            $data['process'] = 6;
            $result = self::where(['id' => $id])->update($data);
            if (false === $result) {
                // 验证失败 输出错误信息
                throw new Exception('修改信息错误');
            }
            Event::where(['relation_type' => 'workorder', 'relation_id' => $id, 'type' => 1])
                ->update(['status' => 1]);
            $content = '根据评估结果，继续维修';
            $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
            $params['relation_id'] = $id;
            //创建跟进记录
            StaffSignIn::quickSignIn($workorder['customer_id'], $content, $params);
            $staff = Staff::info();
            //发送通知
            $messageContent = $staff->name . '《' . $workorder['title'] . '》评估继续维修，请您及时审阅';
            $toStaff = [$workorder['create_staff_id'], $workorder['owner_staff_id']];
            $toStaff = implode(',', $toStaff);
            Message::addMessage(Message::WORKORDER_TYPE, $id,  $workorder['owner_staff_id'], $staff->id, $messageContent);

        } elseif ($is_continue == 9) {//取消维修
            $data['process'] = 9;
            $data['status'] = 3;
            $result = self::where(['id' => $id])->update($data);
            if (false === $result) {
                // 验证失败 输出错误信息
                throw new Exception('修改信息错误');
            }

            //取消任务
            Event::where(['relation_type' => 'workorder', 'relation_id' => $id])->update([
                'status' => 3]);

            $content = '销售根据评估结果，取消维修';
            $params['relation_type'] = StaffSignIn::WORKORDER_TYPE;
            $params['relation_id'] = $id;
            //创建跟进记录
            StaffSignIn::quickSignIn($workorder['customer_id'], $content, $params);

            $staff = Staff::info();
            $messageContent = $staff->name . '《' . $workorder['title'] . '》评估取消维修，请您及时审阅';

            Message::addMessage(Message::WORKORDER_TYPE, $id, $workorder['owner_staff_id'], $staff->id, $messageContent);

        }

        return true;
    }

    public static function getWorkorderNumber()
    {
        return 'S' . date('ymd') . rand(100, 999);
    }

    //工单完成
    public static function setComplete($workorder_id)
    {
        $staff=Staff::info();
        $row=self::get($workorder_id);
        //日程完成
        Event::where(['relation_type' => 'workorder', 'relation_id' => $workorder_id])
            ->update(['status' => 2]);
        if (in_array($row['workorder_type'], self::getVisitType())) {
            //回访客户通知
            Message::addMessage(Message::WORKORDER_TYPE, $row['id'], $row['create_staff_id'], $staff->id, '《' . $row->title . '》工单已完成，请您尽快回访客户!');
        }
        if($row['is_pay'] == 1){
            //发送通知
            Message::addMessage(Message::WORKORDER_RECEIVABLES, $workorder_id,$row['create_staff_id'],$staff->id, '《' . $row->title . '》任务已完成，请您及时确认回款情况！');
        }
        return true;
    }

    //获取回访工单类型
    public static function getVisitType()
    {
        return ['上门安装', '上门维修','配件安装'];
    }
}
